package com.tenglong.teacher.ui.downApk.iPresenter;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.cuotibao.zhuoxiao.basics.utils.IpUtils;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.google.gson.Gson;
import com.tenglong.teacher.data.resultInfo.CurrentVersionInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.dialog.VersionDialog;
import com.tenglong.teacher.ui.downApk.IContract;
import com.tenglong.teacher.ui.downApk.iView.ViewPresenter;
import com.tenglong.teacher.ui.downApk.service.APKDownloadService;

import java.io.File;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author hdx on 2019/2/26.
 */
public abstract class BaseServicePresenter implements IContract.Presenter {
    private IContract.View mView;
    private ServiceConnection mConn;
    private String mUrl;

    public BaseServicePresenter(IContract.View view) {
        this.mView = view;
    }

    @Override
    public void checkUpdate(final int oldVersion, final IContract.CheckUpdateListener listener) {
        CreateRequestEntity.getWebServiceLogin().getVersion().enqueue(new Callback<BaseResult<CurrentVersionInfo>>() {
            @Override
            public void onResponse(Call<BaseResult<CurrentVersionInfo>> call, Response<BaseResult<CurrentVersionInfo>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    if (response.body().data != null) {
                        Log.e("versionInfo",new Gson().toJson(response.body().data));
                        response.body().data.versionUrl = IpUtils.getImageUrl(response.body().data.versionUrl);
                        listener.onIsHasNewsVersion(oldVersion < response.body().data.versionCode);
                        if (oldVersion < response.body().data.versionCode) {
                            mUrl = response.body().data.versionUrl;
                            dialog(response.body().data);
                        } else {
                            mView.yetNewsVersion();
                        }
                    }
                } else {
                    listener.onIsHasNewsVersion(false);
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<CurrentVersionInfo>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                listener.onIsHasNewsVersion(false);
            }
        });
    }

    private void dialog(CurrentVersionInfo data) {
        mView.showUpdate(data, new VersionDialog.VersionDialogInterface() {
            @Override
            public void onSyntony(VersionDialog.VerSionType type) {
                if (type == VersionDialog.VerSionType.CON_VERSION_TYPE) {
                    mView.downLoad();
                } else {
                    Context context = mView.getAppContext();
                    if (context instanceof Activity) {
                        ((Activity) context).finish();
                    }
                }
            }
        });
    }


    @Override
    public void downApk(Context context) {
        if (mConn == null) {
            mConn = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    APKDownloadService.DownloadBinder binder = (APKDownloadService.DownloadBinder) service;
                    final APKDownloadService myService = binder.getService();
                    final IContract.INotify notifyPresent = getNotify(myService);
                    myService.load(mUrl, new APKDownloadService.DownloadCallback() {
                        @Override
                        public void onPrepare() {
                            ViewPresenter.DOWN_LOAD_STATUS = 0;
                            notifyPresent.prepare();
                        }

                        @Override
                        public void onProgress(int progress) {
                            ViewPresenter.DOWN_LOAD_STATUS = 1;
                            mView.showProgress(progress);
                            String title = "正在下载：新版本...";
                            notifyPresent.progress(title, progress);
                        }

                        @Override
                        public void onComplete(File file) {
                            ViewPresenter.DOWN_LOAD_STATUS = 0;
                            mView.showComplete();
                            notifyPresent.complete("下载完成，点击安装", myService.getPackageName(), install(file));
                        }

                        @Override
                        public void onFail(String msg) {
                            ViewPresenter.DOWN_LOAD_STATUS = 0;
                            mView.showFail(msg);
                            notifyPresent.fail("新版本", msg);
                        }

                        @Override
                        public Intent install(File file) {
                            return mView.install(file);
                        }
                    });
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };
        }
        Intent intent = new Intent(context, APKDownloadService.class);
        context.bindService(intent, mConn, Service.BIND_AUTO_CREATE);
    }

    @Override
    public void unbind(Context context) {
        if (mConn != null) {
            context.unbindService(mConn);
        }
    }

    public abstract IContract.INotify getNotify(APKDownloadService service);
}
